"""
Flask web application for benchmark visualization.
"""

import os
import argparse
from pathlib import Path
from flask import Flask, render_template, jsonify, request, send_file
import io
import csv

from .loader import ReportLoader
from .scorer import BenchmarkScorer


app = Flask(__name__)
loader = None
scorer = None


def init_app(results_dir: str = "results"):
    """Initialize the application with results directory."""
    global loader, scorer
    
    loader = ReportLoader(results_dir)
    loader.load_all()
    
    if loader.reports:
        scorer = BenchmarkScorer(loader.reports)
    else:
        scorer = None
    
    print(f"Loaded {len(loader.reports)} reports from {results_dir}")


@app.route('/')
def index():
    """Main page."""
    return render_template('index.html')


@app.route('/api/reports')
def get_reports():
    """Get list of loaded reports."""
    if not loader:
        return jsonify({'reports': []})
    
    return jsonify({'reports': loader.get_report_list()})


@app.route('/api/reports/<report_id>')
def get_report(report_id):
    """Get full report data."""
    if not loader or report_id not in loader.reports:
        return jsonify({'error': 'Report not found'}), 404
    
    return jsonify(loader.reports[report_id])


@app.route('/api/models')
def get_models():
    """Get list of all unique models across all reports."""
    if not loader:
        return jsonify({'models': []})
    
    return jsonify({'models': loader.get_all_models()})


@app.route('/api/score', methods=['POST'])
def calculate_scores():
    """Calculate scores for selected reports."""
    if not scorer:
        return jsonify({'error': 'No reports loaded'}), 400
    
    data = request.json
    report_ids = data.get('report_ids')
    baseline_id = data.get('baseline_id')
    models = data.get('models')
    weights = data.get('weights')
    
    # Update baseline if specified
    if baseline_id and baseline_id in loader.reports:
        scorer.baseline_id = baseline_id
    
    # Calculate scores
    result = scorer.calculate_scores(
        report_ids=report_ids,
        models=models,
        weights=weights
    )
    
    return jsonify(result)


@app.route('/api/export', methods=['POST'])
def export_data():
    """Export comparison data."""
    if not scorer:
        return jsonify({'error': 'No reports loaded'}), 400
    
    data = request.json
    report_ids = data.get('report_ids', list(loader.reports.keys()))
    format_type = data.get('format', 'csv')
    
    # Calculate scores
    result = scorer.calculate_scores(report_ids=report_ids)
    
    if format_type == 'csv':
        # Create CSV
        output = io.StringIO()
        writer = csv.writer(output)
        
        # Header
        header = ['Device', 'Total Score', 'Performance', 'Efficiency', 'Resource', 'Stability']
        writer.writerow(header)
        
        # Data rows
        for score in result['scores']:
            row = [
                score['name'],
                score['total_score'],
                score['performance_score'],
                score.get('efficiency_score', 'N/A'),
                score['resource_score'],
                score['stability_score']
            ]
            writer.writerow(row)
        
        # Create response
        output.seek(0)
        return send_file(
            io.BytesIO(output.getvalue().encode('utf-8')),
            mimetype='text/csv',
            as_attachment=True,
            download_name='benchmark_comparison.csv'
        )
    
    elif format_type == 'json':
        return jsonify(result)
    
    else:
        return jsonify({'error': 'Unsupported format'}), 400


@app.route('/api/upload', methods=['POST'])
def upload_report():
    """Upload a new report."""
    if 'file' not in request.files:
        return jsonify({'error': 'No file provided'}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400
    
    if not file.filename.endswith('.json'):
        return jsonify({'error': 'File must be JSON'}), 400
    
    # Save to results directory
    filepath = Path(loader.results_dir) / file.filename
    file.save(filepath)
    
    # Load the new report
    try:
        report_data = loader.load_report(filepath)
        if not report_data:
            return jsonify({'error': 'Invalid report format'}), 400
        
        report_id = filepath.stem
        loader.reports[report_id] = report_data
        
        # Reinitialize scorer
        global scorer
        scorer = BenchmarkScorer(loader.reports)
        
        return jsonify({
            'id': report_id,
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 400


def main():
    """CLI entry point."""
    parser = argparse.ArgumentParser(description='Benchmark Visualization Server')
    parser.add_argument('--port', type=int, default=8080, help='Port to run server on')
    parser.add_argument('--host', type=str, default='127.0.0.1', help='Host to bind to')
    parser.add_argument('--results', type=str, default='results', help='Results directory')
    parser.add_argument('--debug', action='store_true', help='Enable debug mode')
    
    args = parser.parse_args()
    
    # Initialize
    init_app(args.results)
    
    # Run server
    print(f"\n{'='*60}")
    print(f"🚀 Benchmark Visualization Server")
    print(f"{'='*60}")
    print(f"📊 Loaded {len(loader.reports)} reports")
    print(f"🌐 Server running at: http://{args.host}:{args.port}")
    print(f"📁 Results directory: {args.results}")
    print(f"{'='*60}\n")
    
    app.run(host=args.host, port=args.port, debug=args.debug)


if __name__ == '__main__':
    main()

